package com.woniuxy.tmssystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.tmscommons.entity.Menu;
import com.woniuxy.tmssystem.mapper.MenuMapper;
import com.woniuxy.tmssystem.service.MenuService;
import com.woniuxy.tmssystem.vo.MenuVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author：田江涛
 * @Package：com.woniuxy.tmssystem.service.impl
 * @Project：TMS
 * @name：MenuServiceImpl
 * @Date：2024/9/3 16:59
 * @Filename：MenuServiceImpl
 * @Description:
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;
    @Override
    public boolean addMenu(MenuVo menuVo) {
        if (menuVo.getPid()==null){
            menuVo.setPid(0);
        }
        return menuMapper.insert(menuVo)>0;
    }

    @Override
    public List<Menu> getAllMenu() {
        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Menu::getId);
        List<Menu> menus = menuMapper.selectList(lambdaQueryWrapper);
        return buildMenuTree(menus);
    }

    @Override
    public boolean updateMenu(MenuVo menuVo) {
        return menuMapper.updateById(menuVo)>0;
    }

    @Override
    public boolean deleteMenu(Integer id) {
        return menuMapper.deleteById(id)>0;
    }

    @Override
    public List<Menu> getChildMenu(Integer pid) {
        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Menu::getPid,pid);
        return menuMapper.selectList(lambdaQueryWrapper);
    }

    // 构建菜单树
    public List<Menu> buildMenuTree(List<Menu> menus) {
        List<Menu> rootMenus = findRootMenus(menus);
        for (Menu rootMenu : rootMenus) {
            addChildren(rootMenu, menus);
        }
        return rootMenus;
    }

    // 查找根菜单（pid 为 0 的菜单）
    private List<Menu> findRootMenus(List<Menu> menus) {
        List<Menu> rootMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getPid() == 0) {
                rootMenus.add(menu);
            }
        }
        return rootMenus;
    }

    // 递归添加子菜单
    private void addChildren(Menu menu, List<Menu> allMenus) {
        // 初始化children集合，避免为null
        if (menu.getChildren() == null) {
            menu.setChildren(new ArrayList<>());
        }

        for (Menu child : allMenus) {
            if (child.getPid() == menu.getId()) {
                menu.getChildren().add(child);
                addChildren(child, allMenus); // 递归添加子菜单
            }
        }
    }
}
